import React, { forwardRef, useImperativeHandle, useRef } from "react";

interface MyInputProps extends HTMLInputElement {
  focus: () => void;
}

// 添加forwardRef类型的 第二个参数就是ref
//! 元素引用的传递
//? 获取元素的引用 findDOMNode (不推荐)或者createRef
const MyInput = forwardRef<HTMLInputElement>((props, ref) => {
  //
  // useImperativeHandle<HTMLInputElement, MyInputProps>(ref, () => ({
  //   focus: () => {
  //     console.log("触发focus");
  //   },
  // }));
  return <input ref={ref} />;
});

const ForfordRefDemo: React.FC = () => {
  const inputRef = useRef<HTMLInputElement>(null);

  return (
    <div>
      <MyInput ref={inputRef} />
      <button
        onClick={() => {
          if (inputRef.current) {
            inputRef.current.focus();
          }
        }}
      >
        聚焦
      </button>
      <div>ForfordRefDemo</div>
    </div>
  );
};

export default ForfordRefDemo;
